<?php

namespace app\codekey\api;

use app\one_api\api\ApiInit;
use app\codekey\model\UserGroupCodekey as KeyModel;
use app\user\model\User as UserModel;
use app\user\model\UserGroup as GroupModel;

class Gcode extends ApiInit
{

    /**
     * 自助获取兑换码
     *
     * @return void
     * @author 617 <email：723875993@qq.com>
     */
    public function one()
    {
        $data = $this->params;

        $from = isset($data['from']) && !empty($data['from']) ? $data['from'] : '';

        if (!isset($data['device_id']) || !isset($data['model'])) {
            return $this->_error('来源错误，请使用手机微信访问');
        }

        $time = time();
        $ip = get_client_ip(1);

        $uuid = md5($ip . $data['device_id'] . $data['model']);

        $public = config('codekey.top_public');

        $rules = config('codekey.rules');
        $rules = explode('-', $rules);

        foreach ($rules as $key => $val) {
            $str[] = '${S' . ($key + 1) . '}';
            $re_str[] = $val;
        }

        $public = str_replace($str, $re_str, $public);
        $public_switch = (int)config('codekey.share_switch');

        $_result = [
            'public' => $public,
            'public_switch' => $public_switch,
        ];

        $model = new KeyModel;
        $user_model = new UserModel;
        $group_model = new GroupModel;

        // 自动处理过期兑换码
        $_map = [];
        $_map[] = ['status', 'eq', 0];
        $_map[] = ['exp_time', 'gt', 0];
        $_map[] = ['exp_time', 'lt', $time];
        $model->where($_map)->update(['status' => 5]);

        // 是否已激活
        $__map = [];
        $__map[] = ['uuid', 'eq', $uuid];
        $__map[] = ['status', 'eq', 1];
        // 查询当前设备被使用的卡密的用户（同一个设备激活后将无法再次获取兑换码）
        $user_id = $model->where($__map)->value('user_id');
        if (!empty($user_id)) {
            // 查询该用户 用户组
            $group_id = $user_model->where('id', $user_id)->value('group_id');
            // 查询默认用户组
            $default_group_id = $group_model->where('default', '1')->value('id');
            // 检查该用户会员组是否不是默认的
            if ($group_id > $default_group_id) {
                return $this->_error('您已激活成功，会员有效期内无法再次获取', $_result);
            }
        }

        // 获取频次限制 0为不限制
        $count = cache($uuid . 'limit') ? cache($uuid . 'limit') : 1;
        $limit = config('codekey.get_codekey_limit') > 0 ? config('codekey.get_codekey_limit') : 0;
        if($limit == 0) {
        	return $this->_error('暂不接受新用户，请持续关注，感谢支持', $_result, 1000);
        }
        if ($limit > 0 && $count > $limit) {
            return $this->_error('一天内只能获取' . $limit . '次', $_result, 1000);
        }

        $codekey = cache($uuid);
        $exp_time = config('codekey.codekey_exp') > 0 ? $time + (config('codekey.codekey_exp') * 60) : 0;

        if (!$codekey) {
            // 查询是否有可用兑换码
            $map = [];
            $map[] = ['status', 'eq', 0];
            $map[] = ['code_type', 'eq', 1];
            $map[] = ['exp_time', 'gt', $time];
            $map[] = ['uuid', 'eq', $uuid];
            $codekey = $model->where($map)->value('codekey');
            if (!$codekey) {
                // 没有  新生成一个
                $codekey = substr(md5(random(16, 0) . $time), 3, 12);
                $data = [
                    'group_id' => isset($data['group_id']) && !empty($data['group_id']) ? $data['group_id'] : config('commoncfg.member_group_limit'),
                    'codekey' => $codekey,
                    'exp_time' => $exp_time,
                    'ip' => $ip,
                    'device_id' => $data['device_id'],
                    'model' => $data['model'],
                    'uuid' => $uuid,
                    'from_user' => $from,
                ];
                $model->save($data);
                cache($uuid . 'limit', $count + 1);
            }
            cache($uuid, $codekey, 180);
        }

        $result = [
            'codekey' => config('commoncfg.code_key') . $codekey,
            'exp_time' => $exp_time > 0 ? config('codekey.codekey_exp') . '分钟，请尽快使用，过期无效。' : '无限制',
            'limit' => $limit,
            'public' => $public,
            'public_switch' => $public_switch,
        ];
        return $this->_success('获取成功', $result);
    }
}
